package mamikeji.liaowa.ui.activity.right;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.UpdateImgIdentityBean;
import mamikeji.liaowa.bean.UserIdentityBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.utils.FileUtils;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.selectorImage.MultiImageSelector;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UserIdentityActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "UserIdentityActivity";
    private static final int REQUEST_GALLERY = 101;
    private static final int REQUEST_CAMERA = 100;
    private static final int RESULT_REQUEST_CODE = 102;
    @BindView(R.id.editText_user_identity_content_name)
    EditText editTextUserIdentityContentName;
    @BindView(R.id.textView_identity_imgtype)
    TextView textViewIdentityImgtype;
    @BindView(R.id.linearLayout_user_identity_content_cade)
    LinearLayout linearLayoutUserIdentityContentCade;
    @BindView(R.id.linearLayout_user_identity_content_workprove)
    LinearLayout linearLayoutUserIdentityContentWorkprove;
    @BindView(R.id.linearLayout_user_identity_content_qualifications)
    LinearLayout linearLayoutUserIdentityContentQualifications;
    @BindView(R.id.linearLayout_identity_img)
    LinearLayout linearLayoutIdentityImg;
    @BindView(R.id.imageView_identity_preview)
    ImageView imageViewIdentityPreview;
    @BindView(R.id.textView_user_identity_content_query)
    TextView textViewUserIdentityContentQuery;
    @BindView(R.id.linearLayout_user_identity_content)
    LinearLayout linearLayoutUserIdentityContent;
    @BindView(R.id.imageView_user_identity_static)
    ImageView imageViewUserIdentityStatic;
    @BindView(R.id.textView_user_identity_static)
    TextView textViewUserIdentityStatic;
    @BindView(R.id.textView_user_identity_static_query)
    TextView textViewUserIdentityStaticQuery;
    @BindView(R.id.linearLayout_user_identity_static)
    LinearLayout linearLayoutUserIdentityStatic;
    @BindView(R.id.multiStateView_identity)
    MultiStateView multiStateViewIdentity;
    @BindView(R.id.imageView_identity_mingpian)
    ImageView imageViewIdentityMingpian;
    @BindView(R.id.imageView_identity_gongzuozheng)
    ImageView imageViewIdentityGongzuozheng;
    @BindView(R.id.imageView_identity_zigezhengshu)
    ImageView imageViewIdentityZigezhengshu;

    private boolean bool_image = false;
    private String image_type = "";
    private int image_name;//图片类型名称
    private Dialog dialog_img;

    private File file_img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_identity);
        ButterKnife.bind(this);
        getBase();
        setTitleLeftBtn();
        setTitleName(R.string.identity_title);

        init();
        userimg_dig();
    }

    private void init() {
        getMyCertification();
    }

    /**
     * 获取认证消息
     */
    private void getMyCertification() {
        Map<String, String> formMap = new HashMap<>();
        ForHttp.setMsg(HttpApi.ROOT_PATH
                        + HttpApi.GetMyCertification + "?" + HttpKey.identity_usercode + "=" + ForPreference.getString(ForContents.USER_CODE)
                , formMap, new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        ForLog.i(TAG, e.getMessage());
                        ForToast.showToast(R.string.intent_error);
                        multiStateViewIdentity.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                    }

                    @Override
                    public void onResponse(String response) {
                        ForLog.i(TAG, response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString(HttpKey.STATUS);
                            if ("200".equals(status)) {
                                UserIdentityBean bean = new Gson().fromJson(response, UserIdentityBean.class);
                                if (bean != null) {
                                    if (bean.getData().getId() == 0) {
                                        linearLayoutIdentityImg.setVisibility(View.VISIBLE);
                                        imageViewIdentityPreview.setVisibility(View.GONE);

                                        linearLayoutUserIdentityContent.setVisibility(View.VISIBLE);
                                        linearLayoutUserIdentityStatic.setVisibility(View.GONE);
                                    } else {
                                        linearLayoutUserIdentityContent.setVisibility(View.GONE);
                                        linearLayoutUserIdentityStatic.setVisibility(View.VISIBLE);

                                        textViewUserIdentityStaticQuery.setVisibility(View.GONE);

                                        switch (bean.getData().getState()) {
                                            case 0:
                                                imageViewUserIdentityStatic.setImageResource(R.drawable.icon_shenhe_n);
                                                textViewUserIdentityStatic.setText(R.string.identity_static_0);
                                                break;
                                            case 1:
                                                imageViewUserIdentityStatic.setImageResource(R.drawable.icon_tongguo_n);
                                                textViewUserIdentityStatic.setText(R.string.identity_static_1);
                                                break;
                                            case 2:
                                                imageViewUserIdentityStatic.setImageResource(R.drawable.icon_weitongguo_n);
                                                textViewUserIdentityStatic.setText(R.string.identity_static_2);

                                                textViewUserIdentityStaticQuery.setVisibility(View.VISIBLE);
                                                break;
                                        }
                                    }
                                    multiStateViewIdentity.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                                } else {
                                    multiStateViewIdentity.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                                }
                            } else {
                                multiStateViewIdentity.setViewState(MultiStateView.VIEW_STATE_ERROR);
                                ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @OnClick({
            R.id.textView_user_identity_static_query,
            R.id.textView_user_identity_content_query,
            R.id.linearLayout_user_identity_content_cade,
            R.id.linearLayout_user_identity_content_workprove,
            R.id.linearLayout_user_identity_content_qualifications
    })
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.textView_user_identity_static_query:
                linearLayoutIdentityImg.setVisibility(View.VISIBLE);
                imageViewIdentityPreview.setVisibility(View.GONE);

                linearLayoutUserIdentityContent.setVisibility(View.VISIBLE);
                linearLayoutUserIdentityStatic.setVisibility(View.GONE);
                break;
            case R.id.textView_user_identity_content_query:
                if (TextUtils.isEmpty(editTextUserIdentityContentName.getText().toString())) {
                    ForToast.showToast(R.string.identity_error_name);
                    return;
                }
                if (!bool_image) {
                    dialog_img.show();
                    return;
                }
                showLoading();
                uploadImage(file_img);
//                ForLog.i("uploadImage", bool_image + "          " + editTextUserIdentityContentName.getText().toString());
                break;
            case R.id.btn_userimg_camera:
                dialog_img.hide();
                photo();
                break;
            case R.id.btn_userimg_album:
                dialog_img.hide();
                MultiImageSelector.create(this)
                        .showCamera(false) // 是否显示相机. 默认为显示
                        .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                        .single() //单选
                        .start(this, REQUEST_GALLERY);
                break;
            case R.id.btn_userimg_cancel:
                dialog_img.hide();
                break;
            case R.id.linearLayout_user_identity_content_cade:
                image_type = "1";
                image_name = R.string.identity_card;
                imageViewIdentityMingpian.setImageResource(R.drawable.icon_mingpian_h);

                imageViewIdentityGongzuozheng.setImageResource(R.drawable.icon_gongzuozheng_n);
                imageViewIdentityZigezhengshu.setImageResource(R.drawable.icon_zhegezheng_n);
                break;
            case R.id.linearLayout_user_identity_content_workprove:
                image_type = "2";
                image_name = R.string.identity_workProve;
                imageViewIdentityGongzuozheng.setImageResource(R.drawable.icon_gongzuozheng_h);

                imageViewIdentityMingpian.setImageResource(R.drawable.icon_mingpian_n);
                imageViewIdentityZigezhengshu.setImageResource(R.drawable.icon_zhegezheng_n);
                break;
            case R.id.linearLayout_user_identity_content_qualifications:
                image_type = "3";
                image_name = R.string.identity_qualifications;
                imageViewIdentityZigezhengshu.setImageResource(R.drawable.icon_zhegezheng_h);

                imageViewIdentityMingpian.setImageResource(R.drawable.icon_mingpian_n);
                imageViewIdentityGongzuozheng.setImageResource(R.drawable.icon_gongzuozheng_n);
                break;
        }
    }

    private Button btn_userimg_camera, btn_userimg_album, btn_userimg_cancel;

    public void userimg_dig() {
        dialog_img = new Dialog(UserIdentityActivity.this, R.style.ActionSheetDialogStyle);
        View inflate = LayoutInflater.from(UserIdentityActivity.this).inflate(R.layout.dialog_usermsg_img, null);

        btn_userimg_camera = (Button) inflate.findViewById(R.id.btn_userimg_camera);
        btn_userimg_album = (Button) inflate.findViewById(R.id.btn_userimg_album);
        btn_userimg_cancel = (Button) inflate.findViewById(R.id.btn_userimg_cancel);

        btn_userimg_camera.setOnClickListener(this);
        btn_userimg_album.setOnClickListener(this);
        btn_userimg_cancel.setOnClickListener(this);

        dialog_img.setContentView(inflate);
        Window dialogWindow = dialog_img.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;
        lp.width = (int) getResources().getDisplayMetrics().widthPixels - 30; // 宽度
        dialogWindow.setAttributes(lp);
    }

    private String mImageFileName; // 随机缓存照片名

    public void photo() {
        // 随机缓存照片名
        mImageFileName = FileUtils.getFileNameForSystemTime(".jpg");
        // 首先判断SD卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mImageFileName)));
            startActivityForResult(intent, REQUEST_CAMERA);
        } else {
            ForToast.showToast("内存卡不存在");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_GALLERY) {
                List<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                if (mSelectPath != null && mSelectPath.size() > 0) {
                    Uri uri = Uri.fromFile(new File(mSelectPath.get(0)));
                    startPhotoZoom(uri);
                }
            } else if (requestCode == REQUEST_CAMERA) {
                File file = new File(Environment.getExternalStorageDirectory() + "/" + mImageFileName);
                Uri uri = Uri.fromFile(file);
                startPhotoZoom(uri);
            } else if (requestCode == RESULT_REQUEST_CODE) {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap bitmap = extras.getParcelable("data");
                    //Drawable drawable = new BitmapDrawable(this.getResources(), bitmap);
//                    imageView_dynamic_titleimg.setImageDrawable(drawable);
                    FileUtils.saveBitmap(bitmap, "avatar");
                    File file = new File(FileUtils.SDPATH + "avatar.jpg");
                    if (file != null) {
                        bool_image = true;

                        linearLayoutIdentityImg.setVisibility(View.GONE);
                        imageViewIdentityPreview.setVisibility(View.VISIBLE);

                        imageViewIdentityPreview.setImageBitmap(bitmap); //设置Bitmap预览图
                        textViewIdentityImgtype.setText(image_name);

                        file_img = file;
                    }
                }
            }
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 2);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 526);
        intent.putExtra("outputY", 232);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    //     232   116
    //     526   263

//    private void compress(File f) {
//        Luban.compress(this, f)
//                .putGear(Luban.CUSTOM_GEAR)
//                .setMaxSize(300)
//                .launch(new OnCompressListener() {
//                    @Override
//                    public void onStart() {}
//
//                    @Override
//                    public void onSuccess(File file) {
//                        uploadImage(file);
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        ForToast.showToast("压缩失败");
//                        ForLog.i("compresscompresscompress", "" + e.toString());
//                    }
//                });
//    }

    private void uploadImage(File file) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("file", "file.jpg", RequestBody.create(MultipartBody.FORM, file));
        builder.addFormDataPart("id", ForPreference.getString(ForContents.USER_CODE));
        MultipartBody body = builder.build();

        OkHttpClient okHttpClient = new OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(HttpApi.ROOT_PATH + HttpApi.UPLOAD_identity_IMG)
                .post(body)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("失败:" + e.toString());
                hideLoading();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                ForLog.i("json_json", json + "");
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        UpdateImgIdentityBean uploadImageBean = new Gson().fromJson(json, UpdateImgIdentityBean.class);
                        if (uploadImageBean.getStatus() == 200) {
                            List<UpdateImgIdentityBean.ListEntity> imageList = uploadImageBean.getList();
                            if (imageList != null && imageList.size() > 0) {
                                submitCertification(editTextUserIdentityContentName.getText().toString(), imageList.get(0).getFileUrl());
                            }
                        } else {
                            ForToast.showToast(uploadImageBean.getMessage());
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 提交认证消息
     */
    private void submitCertification(String name, String imgurl) {
        ForHttp.setMsg(
                HttpApi.ROOT_PATH + HttpApi.SubmitCertification + "?"
                        + HttpKey.identity_submit_usercode + "=" + ForPreference.getString(ForContents.USER_CODE) + "&"
                        + HttpKey.identity_submit_name + "=" + name + "&"
                        + HttpKey.identity_submit_category + "=" + image_type + "&"
                        + HttpKey.identity_submit_imgurl + "=" + imgurl
                , new HashMap<String, String>(), new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        ForLog.i(TAG, e.getMessage());
                        ForToast.showToast(R.string.intent_error);
                        hideLoading();
                    }

                    @Override
                    public void onResponse(String response) {
                        ForLog.i(TAG, response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString(HttpKey.STATUS);
                            if ("200".equals(status)) {
                                finish();
                            } else {
                                ForToast.showToast("失败了！");
                            }
                            hideLoading();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 加载本地图片
     *
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}
